<?php

/**
 * This file is part of the Framework03 PHP framework.
 * @author Walter Tamboer
 * @package Framework03
 */

/**
 * The custom Loader class of the FW library.
 */
class FW_Loader
{
    /**
     * The autoloader callback function which does the actual loading of the class or interface.
     * @param $name The name of the class or interface to load.
     */
    private static function autoLoad($name)
    {
        $path = str_replace('_', '/', $name) . '.php';

        /*if (!is_file($path))
        {
            require_once 'FW/Exception.php';
            throw new FW_Exception("Failed to load '$path', file not found.");
        }*/

        require_once $path;
    }

    /**
     * Register the autoloader which helps you loading classes and interfaces automaticly.
     */
    public static function startAutoLoading()
    {
        spl_autoload_register(array('FW_Loader', 'autoLoad'));
    }

    /**
     * Unregister the current registered autoloader and stops the automatic loading of classes and interfaces.
     */
    public static function stopAutoLoading()
    {
        spl_autoload_unregister(array('FW_Loader', 'autoLoad'));
    }

    /**
     * Checks if the given path is readable.
     * @param string $path The path to check on.
     * @return boolean Returns true when the path is readable; false otherwise.
     */
    public static function isReadable($path)
    {
        return is_readable($path);
    }

    /**
     * Loads the given file.
     * @param string $path The path to load.
     */
    public static function loadFile($path)
    {
        include $path;
    }

    /**
     * Checks if the given class exists.
     * @param string $name The name of the class.
     * @return bool
     */
    public static function classExists($className)
    {
        $includePath = explode(PATH_SEPARATOR, get_include_path());
        $path = str_replace('_', '/', $className) . '.php';

        foreach ($includePath as $dir)
        {
            $final = $dir . '/' . $path;

            if (file_exists($final))
                return true;
        }

        return false;
    }
}
